<?php
namespace app\api\controller;

use app\common\model\AppleDebtBacked;
use app\common\model\AppleRepayPlan;
use app\common\model\NokiaMember;
use app\common\model\OppoOrder;
use app\common\model\OppoOrderGoods;
use app\common\model\OppoOrderMember;
use app\common\model\SonyOrderRepay;
use app\common\service\AlipayService;
use app\common\service\DeptBackedService;
use think\admin\Controller;
use think\admin\extend\CodeExtend;

class Web extends Controller
{
    //用户信息
    protected $user;

    private $key = "5e692e86ec76c1385a7229b4ed0e260e";
    public function initialize()
    {
        $action = $this->request->action();
        $params = $this->_vali(['user_id.default' => '', 'token.default' => '', 'timestamp.default' => '']);
        if($action != 'login'){
            $token = $this->request->header('api-token');
            if (empty($token)) $this->error('重新登录', '{-null-}', -1);
            if(!$params['user_id'] || !$params['timestamp']){
                $this->error('参数错误', '{-null-}', 422);
            }
            $time = time();
            if($time > ($params['timestamp'] + 86400 * 7)) $this->error('请登录', '{-null-}', 422);
            $sign = md5($this->key . $params['user_id'] . $params['timestamp']);
            if($sign != $token){
                $this->error('异常', '{-null-}', 422);
            }
            $this->user = NokiaMember::where('member_id', $params['user_id'])->find();
            if(empty($this->user)){
                $this->error('请登录');
            }
        }
    }

    /**
     * 登录
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login()
    {
        $params = $this->_vali(['mobile.require' => '手机号不能为空！', 'password.require' => '密码不能为空']);
        $pwd = md5($params['password']);
        $where = [
            'mobile' => $params['mobile'],
            'login_password' => $pwd
        ];
        $data = NokiaMember::where($where)->find();
        if(empty($data)){
            $this->error('账号密码错误');
        }
        $res = [
            'user_id' => $data['member_id'],
            'headimg' => 'https://cdn.yibaozulin.com/b0/0b83f066719dc93b12073d12f89ed9.png',
            'mobile' => $data['mobile']
        ];
        $this->success('success', $res);
    }

    /**
     * 用户信息
     * @return void
     */
    public function info()
    {
        $data = $this->user;
        $res = [
            'member_id' => $data['member_id'],
            'headimg' => 'https://cdn.yibaozulin.com/b0/0b83f066719dc93b12073d12f89ed9.png',
            'mobile' => $data['mobile']
        ];
        $this->success('success', $res);
    }

    public function tablist()
    {
        $params = $this->request->request();
        $uid = $this->user['member_id'];

        $tabName = ['全部', '待归还', '已完成'];

        $list = [];

        foreach ($tabName as  $value) {
            $tem['title'] = $value;
            $tem['status'] = 0;
            $tem['is_timeout'] = 0;
            switch ($value) {
                case '全部':
                    $tem['number'] = OppoOrder::where(['member_id' => $uid])->whereIn('status', [5,6])->count();
                    break;
                case '待归还':
                    $tem['number'] = OppoOrder::where(['member_id' => $uid, 'status' => 5])->count();
                    $tem['status'] = 5;
                    break;
                case '已完成':
                    $tem['number'] = OppoOrder::where(['member_id' => $uid, 'status' => 6])->count();
                    $tem['status'] = 6;
                    break;
            }
            $tem['badge']['arrow']  = $tem['number'] < 1 ? false : true;
            $tem['badge']['stroke'] = $tem['number'] < 1 ? false : true;
            $tem['showBadge']       = $tem['number'] < 1 ? false : true;
            $list[]                 = $tem;
        }

        $this->success('ok', $list);
    }

    /**
     * 订单列表
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderLst()
    {
        $uuid = $this->user['member_id'];
        $map = ['member_id' => $uuid, 'del_flag' => 0];
        $status = $this->request->get('status');
        if($status){
            $map['status'] = $status;
        }

        $result = OppoOrder::mQuery()->equal('order_id')->field('id, order_id,plan_index, status, goods_nums, deposit_amount,goods_name,goods_sku_name,goods_sku_pic,first_pay_amount,sign_price')->where($map)->order('id desc')->page(true, false, false, 20);

        //if (count($result['list']) > 0) OrderService::instance()->listData($result['list']);
        if (count($result['list']) > 0) {
            foreach ($result['list'] as &$v) {

                if($v['status'] == 5){
                    $v['status_text'] = '待归还';
                }
                if($v['status'] == 6){
                    $v['status_text'] = '已完成';
                }

                $v['items'][] = $v;
            }
        }

        $this->success('获取订单列表成功！', $result);
    }

    /**
     * 订单详情
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderShow()
    {
        $data = $this->_vali([
            'order_id.require' => '订单编号不能为空'
        ]);

        $map = ['del_flag' => 0 ,'order_id' => $data['order_id'] ];

        $result = OppoOrder::where($map)->field(['id, order_id,member_id,plan_index, status, goods_nums, deposit_amount,goods_name,goods_sku_name,goods_sku_pic,first_pay_amount,sign_price,rent_date,back_date,buy_amount,monthly_price,price,plan_index'])->find()->toArray();

        if(empty($result)){
            $this->error('订单不存在');
        }

        $is_rent = 1;
        $result['is_rent'] = $is_rent;
        //组装每期数据
        $term_info = [];

        $term_info =  AppleRepayPlan::where(['order_id' => $data['order_id'], 'del_flag'=>0, 'bill_type' => 1])->field('id,plan_id,order_id,plan_index,plan_date,plan_amount,plan_total_amount,overdue_day,overdue_fine,have_overdue,status')->select()->toArray();
        $deptArr = DeptBackedService::getPlanDept($data['order_id']);
        foreach ($term_info as &$vo) {
            $pay = isset($deptArr['pay'][$vo['plan_index']]) ? $deptArr['pay'][$vo['plan_index']] : 0;
            $vo['pay'] = $pay;
            $vo['shengyu'] = $vo['plan_total_amount'] - $pay;
        }
        $result['term_info']      = $term_info;
        $data['list'] = $result;

        $this->success('获取订单数据成功！', $data);
    }

    /**
     * 支付宝支付
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function pay()
    {
        $data = $this->_vali([
            'member_id.value'       => $this->user['id'],
            'expact.require'   => '代扣期数不能为空',
            'order_id.require' => '订单编号不能为空',
            'plan_id.require' => '还款计划id不能为空'
        ]);

        //$orderInfo = OppoOrder::where(['order_id' => $data['order_id']])->find();

        $plan = AppleRepayPlan::where(['order_id' => $data['order_id'],'plan_index' => $data['expact']])->find();

        if (empty($plan)) {
            $this->error("扣费信息不存在,请联系客服");
        }

        if ($plan['status'] == 1){
            $this->error("本期结清,请勿重复还款");
        }
        $pay = 0;
        //还款记录
        $debtBacked = AppleDebtBacked::mk()->where(['order_id' => $data['order_id'], 'plan_index' => $data['expact'], 'status' => 1])->select();
        foreach ($debtBacked as $vd) {
            $amount = $vd['payment_amount'];
            $pay = isset($pay) ? bcadd($pay, $amount, 2) : $amount;
            if ($vd['credit_amount'] > 0) {
                $pay = bcadd($pay, $vd['credit_amount'], 2);
            }
            if (in_array($vd['bill_type'], [7, 11])) {
                $pay = isset($pay) ? bcsub($pay, $amount) : 0 - $amount;
            }
        }
        $shengyu = $plan['plan_total_amount'] - $pay;

        $params = [
            'out_trade_no' => $data['order_id']."P".rand(10000,99999).rand(10000,99999),
            'total_amount' => $shengyu,
            'subject' => '缤纷趣租-【'.$data['order_id'].'】-主动支付租金(第'.$data['expact']."期)"
        ];
        $res = (new AlipayService())->h5Pay($params);

        //用户信息
        $userInfo = OppoOrderMember::mk()->where(['order_id' => $plan['order_id'], 'member_id' => $plan['member_id']])->find();
        //付款单
        $log = [
            'repay_id' => CodeExtend::uniqidDate(18, 'RE'),
            'bill_id' => '',
            'plan_id' => $plan['plan_id'],
            'plan_index' => $plan['plan_index'],
            'order_id' => $plan['order_id'],
            'member_id' => $plan['member_id'],
            'biz_type' => 1,
            'repay_type' => $plan['status'] == 2 ? 2 : 0,
            'pay_method' => 2,
            'payable_amount' => $plan['plan_total_amount'],
            'pay_amount' => $shengyu,
            'remaining_amount' => 0,
            'rent_amount' => $plan['plan_amount'],
            'fine' => $plan['overdue_fine'],
            'deduction_amount' => 0,
            'repay_platform' => 0,
            'repay_name' => '',
            'repay_amount' => $shengyu,
            'repay_voucher' => "",
            'repay_remark' => "",
            'suggest' => 1,
            'pay_id' => $params['out_trade_no'],
            'status' => 0,
            'repay_time' => date('Y-m-d H:i:s'),
            'creater' => '支付宝H5',
            'tenant_id' => 10000,
            'member_name' => $userInfo['real_name'],
            'mobile' => $userInfo['mobile'],
            'merchant_id' => $plan['merchant_id'],
            'shop_name' => $plan['shop_name'],
        ];
        SonyOrderRepay::mk()->insert($log);
        $this->success('nowpay', $res);
    }
}